<template>
  <div class="wrapper">
    <el-card>
      <el-page-header :content="title" @back="$router.back()" />
    </el-card>
    <!-- 基本设置 -->
    <el-card class="mt-4">
      <template #header>
        <div>
          <span>基本设置</span>
        </div>
      </template>
      <el-form :model="formData" :rules="formRules" ref="formRef" label="200px">
        <el-form-item label="活动类型" prop="type">
          <el-radio-group v-model="formData.type" :disabled="type == 'edit'">
            <el-radio :value="1" size="large">刮刮乐</el-radio>
            <el-radio :value="2" size="large">二维码</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-row>
          <el-col :span="8">
            <el-form-item label="活动标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入活动标题"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商家" prop="merchantId">
              <el-select v-model="formData.merchantId" filterable remote reserve-keyword placeholder="输入选择商家"
                :remote-method="searchMerchants" :loading="merchantsLoading" style="width: 240px">
                <el-option v-for="item in merchants" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动名额" prop="num">
              <el-input-number :disabled="type == 'edit' && formData.type == 1" @change="autoCompleCodeNo"
                v-model="formData.num" placeholder="0"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="活动开始日期" prop="startTime">
              <el-date-picker v-model="formData.startTime" type="datetime" placeholder="开始时间"
                value-format="YYYY-MM-DD HH:mm" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="结束日期" prop="endTime">
              <el-date-picker v-model="formData.endTime" type="datetime" placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-tabs v-model="activeTabsName" @tab-click="handleChangeTabs">
        <!-- 绑定卡片 -->
        <el-tab-pane label="绑定卡片" name="1" v-if="formData.type === 1">
          <el-row>
            <el-col :span="7">
              <el-form-item label="前缀" prop="startCodeId">
                <el-input :disabled="type == 'edit' && formData.type === 1" v-model="formData.prefix"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="4">
              <el-form-item label="起始编号" prop="startCodeId">
                <el-input-number :disabled="type == 'edit' && formData.type === 1" v-model="formData.startCodeId"
                  @change="startCodeIdChangeEvent"></el-input-number>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="5">
              <el-form-item label="结束编号" prop="startCodeId">
                <el-input-number v-model="formData.endCodeId" disabled></el-input-number>
              </el-form-item>
            </el-col> -->

          </el-row>
          <el-row>
            <el-col :span="1">
              <!-- <el-button style="margin-left: 8px" type="info" plain @click="handleCheckCard">
                检测是否可用
              </el-button> -->
              <div>
                <span>编号：</span>
              </div>
            </el-col>
            <el-col :span="5">
              <div v-for="(item, index) in formData.activityCodeNoList" :key="index">
                <span>{{ item.text }}</span>
              </div>
            </el-col>

          </el-row>
        </el-tab-pane>

        <!-- 抽奖模版 -->
        <el-tab-pane label="抽奖模版" name="2">
          <el-row>
            <el-col :span="12">
              <el-form-item label="模版" prop="drawId">
                <el-select :disabled="type == 'edit' && formData.type === 1" v-model="formData.drawId" filterable remote
                  reserve-keyword placeholder="选择模版" :remote-method="searchDraws" :loading="drawsLoading"
                  style="width: 240px">
                  <el-option v-for="item in draws" :key="item.id" :label="item.title" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="启用自定义奖品图片">
                <el-switch v-model="formData.isCustomPrizeImg" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-for="(item, index) in formData.activityPrizeList" :key="index">
            <el-col :span="7">
              <el-form-item :label="item.prizeLevel" :prop="'activityPrizeList.' + index + '.prizeId'" :rules="[
                {
                  required: true,
                  message: '必须选择奖品',
                  trigger: 'blur',
                },
              ]">
                <el-select :disabled="type == 'edit' && formData.type === 1"
                  v-model="formData.activityPrizeList[index].prizeId" filterable remote reserve-keyword
                  placeholder="选择奖品" :remote-method="searchPrize" :loading="prizeLoading" style="width: 240px">
                  <el-option v-for="prize in pizes" :key="prize.id" :label="prize.name" :value="prize.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item label="分配数量" prop="num">
                <el-input-number v-model="formData.activityPrizeList[index].num"
                  :disabled="index === 0 || type == 'edit' && formData.type === 1"
                  @change="computedPrize"></el-input-number>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="8">
              <el-form-item label="概率" prop="pprobability">
                <el-input v-model="formData.activityPrizeList[index].probability" disabled>
                  <template #append>%</template>
                </el-input>
              </el-form-item>
            </el-col> -->
          </el-row>


        </el-tab-pane>

        <!-- 规则描述 -->
        <el-tab-pane label="活动规则" name="3">
          <el-row>
            <el-col :span="12">
              <el-form-item label="限每日抽奖人数" prop="isDayLimitNum">
                <el-radio-group v-model="formData.isDayLimitNum">
                  <el-radio :value="0">不限制</el-radio>
                  <el-radio :value="1">限制</el-radio>
                </el-radio-group>
                <el-input-number class="ml-4" v-if="formData.isDayLimitNum" v-model="formData.dayLimitNum"
                  min="1"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="限每个用户抽奖次数" prop="isDayLimitNum">
                <el-radio-group v-model="formData.isClientLimitNum">
                  <el-radio :value="0">不限制</el-radio>
                  <el-radio :value="1">限制</el-radio>
                </el-radio-group>
                <el-input-number class="ml-4" v-if="formData.isClientLimitNum" v-model="formData.clientLimitNum"
                  min="1"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

        </el-tab-pane>
        <!-- 页面描述 -->
        <el-tab-pane label="抽奖页面描述" name="4">
          <el-row v-for="(item, index) in formData.rulesDesc">
            <el-col :span="24">
              <el-form-item :label="index + 1" :prop="'rulesDesc.' + index" :rules="[
                {
                  required: true,
                  message: '必须填写',
                  trigger: 'blur',
                },
              ]">
                <el-input v-model="formData.rulesDesc[index]" style="width: 400px"
                  :autosize="{ minRows: 1, maxRows: 4 }" type="textarea"></el-input>
                <el-button style="margin-left: 15px" type="primary" @click="addRuleDesRow" plain
                  v-if="index === formData.rulesDesc.length - 1">+</el-button>
                <el-button style="margin-left: 15px" type="warning" @click="delRuleDesRow(index)" v-if="index !== 0"
                  plain>-</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <!-- 客服配置 -->
        <el-tab-pane label="客服" name="5">
          <el-row>
            <el-col :span="6">
              <el-form-item label="联系电话" prop="title">
                <el-input v-model="formData.kefuPhone" placeholder="请输入联系电话"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="flex">
            <span class="mr-4">客服二维码</span>
            <div>
              <material-picker v-model="formData.kefuQrImg" :limit="1" />
              <div class="form-tips">建议尺寸：100*100像素，支持jpg，jpeg，png格式</div>
            </div>
          </div>
        </el-tab-pane>
        <!-- 客户信息 -->
        <el-tab-pane label="客户信息" name="6">
          <el-row>
            <el-col :span="12">
              <el-form-item label="手机号" prop="isBindClientPhone">
                <el-radio-group v-model="formData.isBindClientPhone">
                  <el-radio :value="1">收集</el-radio>
                  <el-radio :value="0">忽略</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="姓名" prop="isBindClientPhone">
                <el-radio-group v-model="formData.isBindClientName">
                  <el-radio :value="1">收集</el-radio>
                  <el-radio :value="0">忽略</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="地址" prop="isBindClientPhone">
                <el-radio-group v-model="formData.isBindClientAddress">
                  <el-radio :value="1">收集</el-radio>
                  <el-radio :value="0">忽略</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

        </el-tab-pane>
      </el-tabs>
    </el-card>

    <footer-btns>
      <el-button type="primary" @click="handleSubmit">
        保存
      </el-button>
    </footer-btns>
  </div>
</template>
<script lang="ts" setup>
import type { FormInstance, TabsPaneContext } from 'element-plus'
import { addApi, editApi } from '@/api/activity/activity'
import { listsApi as getMerchantListsApi } from '@/api/merchant'
import { listsApi as getPizesListsApi } from '@/api/activity/pize'
import { listsApi as getDrawListsApi } from '@/api/activity/draw'
import { dictDataLists } from '@/api/setting/dict'
import feedback from '@/utils/feedback'
import { computed, onMounted, reactive, ref, shallowRef, watch } from 'vue'
import { detailApi } from '@/api/activity/activity'
import { useDictOptions } from '@/hooks/useDictOptions'
import { checkCode, getCodeNoApi } from '@/api/activity/code'
const route = useRoute()
const router = useRouter()
const { type, id } = route.query
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()

const title = computed(() => {
  return type == 'edit' ? '编辑活动' : '新增活动'
})

const { optionsData } = useDictOptions<{
  prizeLevel: Array<{
    id: number
    name: string
    value: number
    dictTypeId: number
  }>
}>({
  prizeLevel: {
    api: dictDataLists,
    params: { dictType: 'prize_level' },
    transformData(data: any) {
      return data.lists
    },
  },
})
interface IActivityPrizes {
  id: number
  prizeIndex: number
  prizeId: number
  prizeLevelId: number
  prizeLevel: string
  num: number
  probability: number
}
const formData = reactive({
  id: '', //活动id
  type: 1,//活动类型
  title: '', //活动标题
  merchantId: '', //商户id
  num: 0, //活动名额
  drawId: '', //H5模版id
  isDayLimitNum: 0, //是否限制每日抽数
  dayLimitNum: 0, //限制每日抽数
  isClientLimitNum: 1,//是否限制用户抽数
  clientLimitNum: 1,//用户抽奖次数
  startTime: '', //活动开始时间
  endTime: '', //活动结束时间
  status: 1, //状态
  remark: '', //备注
  rulesDesc: ['asdfasdfsd', 'dfasdfasd', 'fasdfasdf'] as Array<string>, //规则说明
  activityPrizeList: [] as any[],
  prefix: 'NO',
  startCodeId: 0,
  endCodeId: 0,
  cancelStartTime: '',
  cancelEndTime: '',
  kefuQrImg: "",
  kefuPhone: "",
  isBindClientPhone: 1, //是否绑定用户手机号
  isBindClientName: 0,
  isBindClientAddress: 0,
  activityCodeNoList: [{ codeIdStart: 0, codeIdEnd: 0, totalNum: 0, text: "" }],
  isCustomPrizeImg: 0,
})

watch(() => formData.isDayLimitNum, (newValue, oldValue) => {
  if (!newValue) {
    formData.dayLimitNum = 0
  }
})
watch(() => formData.isClientLimitNum, (newValue, oldValue) => {
  if (!newValue) {
    formData.clientLimitNum = 0
  }
})
const computedEndCodeId = () => {
  formData.endCodeId = Number(formData.num) + Number(formData.startCodeId) - 1
}
const startCodeIdChangeEvent = () => {
  computedEndCodeId()
  autoCompleCodeNo()
}
const getPrizesRows = (drawId: number) => {
  formData.activityPrizeList = []
  const draw = draws.value.find((item: any) => item.id == drawId)
  for (let index = 0; index < draw.prizeNum; index++) {
    formData.activityPrizeList.push({
      id: index,
      prizeIndex: index,
      prizeId: null,
      prizeLevelId: '',
      prizeLevel: optionsData.prizeLevel.find(
        (item: any) => item.value == index,
      )!.name,
      num: 0,
      probability: 0,
    })
    if (index === 0) {
      formData.activityPrizeList[index].num = formData.num
    }
  }
}
const setPrizesRows = () => {
  // 赋值奖品
  backPrizes.value.forEach((item: any, index: any) => {
    formData.activityPrizeList[item.prizeIndex].prizeId = item.prizeId
    formData.activityPrizeList[item.prizeIndex].prizeLevelId = item.prizeLevelId
    formData.activityPrizeList[item.prizeIndex].num = item.num
  })
}

const validatePrize = (rule: any, value: any, callback: any) => {
  console.log('value', value)
  if (!value) {
    callback(new Error('请选择奖品'))
  }
}
// 计算prizes数组中prizeLevelId为0的num值 和概率
const computedPrize = () => {
  const totalPrizeNum = formData.activityPrizeList.reduce((acc, cur) => {
    return cur.id === 0 ? acc : acc + cur.num
  }, 0)

  const totalNum = Number(formData.num)
  if (isNaN(totalNum)) {
    console.warn('formData.num is not a valid number')
    return
  }
  formData.activityPrizeList[0].num = totalNum - totalPrizeNum
  //计算概率
  formData.activityPrizeList.forEach((item: any) => {
    item.probability = (item.num / totalNum) * 100
  })
}
watch(
  () => formData.drawId,
  newValue => {
    getPrizesRows(Number(newValue))
  },
)
const formRules = reactive({
  title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
  merchantId: [{ required: true, message: '请选择商户', trigger: 'blur' }],
  num: [{ required: true, message: '请输入活动名额', trigger: 'blur' }],
  drawId: [{ required: true, message: '请选择H5模版', trigger: 'blur' }],
  isBindClientPhone: [
    { required: true, message: '请选择是否绑定手机号', trigger: 'blur' },
  ],
  isDayLimitNum: [
    { required: true, message: '请选择是否限制每日抽数', trigger: 'blur' },
  ],
  startTime: [
    { required: true, message: '请选择活动开始时间', trigger: 'blur' },
  ],
  endTime: [{ required: true, message: '请选择活动结束时间', trigger: 'blur' }],
})

const activeTabsName = computed(() => {
  return formData.type === 1 ? "1" : "2"
})
const handleChangeTabs = (tab: TabsPaneContext, event: Event) => {
  setPrizesRows()
  computedEndCodeId()
}
const delRuleDesRow = (index: number) => {
  formData.rulesDesc.splice(index, 1) // 移除指定索引的项
}
const addRuleDesRow = () => {
  formData.rulesDesc.push('') // 添加一个新的空字符串项
}
const handleSubmit = async () => {
  await formRef.value?.validate()
  type == 'edit' ? await editApi(formData) : await addApi(formData)
  feedback.msgSuccess('操作成功')
  router.push({
    path: '/lucky/activity',
  })
}


const backPrizes = ref<Array<any>>([])
const setFormData = async (row: any) => {
  const data = await detailApi({
    id: row.id,
  })
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      formData[key] = data[key]
    }
  }
  backPrizes.value = data.activityPrizeList
}
const merchants = ref<Array<any>>([])
const merchantsLoading = ref(false)
const searchMerchants = (name: string) => {
  const merchantsLoading = (ref(false).value = true)
  merchants.value = []
  getMerchantListsApi({
    name,
    status: 1,
    pageSize: 10,
  })
    .then(data => {
      merchants.value = data.lists
      const merchantsLoading = (ref(false).value = false)
    })
    .catch(() => {
      const merchantsLoading = (ref(false).value = false)
      merchants.value = []
    })
}
const draws = ref<Array<any>>([])
const drawsLoading = ref(false)
const searchDraws = (name: string) => {
  drawsLoading.value = true
  draws.value = []
  getDrawListsApi({
    name,
    status: 1,
    pageSize: 10,
  })
    .then(data => {
      draws.value = data.lists
      drawsLoading.value = false
    })
    .catch(() => {
      drawsLoading.value = false
      draws.value = []
    })
}
const autoCompleCodeNo = async () => {
  if (formData.prefix == '' || formData.num == 0 || formData.startCodeId == 0) {
    return
  }
  formData.activityCodeNoList = []
  const data = await getCodeNoApi({
    prefix: formData.prefix,
    num: formData.num,
    codeNoStart: formData.startCodeId,
  })
  formData.activityCodeNoList = data

}
const handleCheckCard = async () => {
  await checkCode({
    prefix: formData.prefix,
    startCodeId: formData.startCodeId,
    endCodeId: formData.endCodeId,
  }).then(res => { })
}
const pizes = ref<Array<any>>([])
const prizeLoading = ref(false)
const searchPrize = (name: string) => {
  prizeLoading.value = true
  pizes.value = []
  getPizesListsApi({
    name,
    pageSize: 10,
  })
    .then(data => {
      pizes.value = data.lists
      prizeLoading.value = false
    })
    .catch(() => {
      prizeLoading.value = false
      pizes.value = []
    })
}
const loadActivityDetail = async () => {
  const data = await detailApi({
    id,
  })
  setFormData(data)
}
onMounted(() => {
  searchMerchants('')
  searchDraws('')
  searchPrize('')
  if (type == 'edit') {
    loadActivityDetail()
  }
})

</script>
<style lang="scss" scoped>
.wrapper {
  .contain {
    width: 800px;
    height: 600px;
    background-color: aqua;

    .el-tabs {
      width: 800px;
      height: 600px !important;
      background-color: aqua;
    }
  }
}
</style>
